<template>
  <div>
    <p-form-model ref="form" :model="form" :rules="rules">
      <div class="connect">
        <div class="item">
          <p-form-model-item label="价格变更编号">
            <span>{{ form.serialNumber }}</span>
          </p-form-model-item>
          <p-form-model-item label="销售组织" prop="salesOrganization">
            <SelectOrg
              :value="form.salesOrganization"
              :has-all="false"
              :allow-clear="false"
              @input="handleOrgChange"
            />
          </p-form-model-item>
          <p-form-model-item ref="time" label="变更年月" prop="startTime">
            <MonthRangePickerPrice
              :start.sync="form.startTime"
              :end.sync="form.endTime"
              :is-empty-array="isEmptyArray"
              @res-is-empty-array="resIsEmptyArray"
              @click="selectTime"
              @blur="
                () => {
                  $refs.time.onFieldBlur();
                }
              "
              @change="
                () => {
                  $refs.time.onFieldChange();
                }
              "
            />
          </p-form-model-item>
        </div>
        <div class="item">
          <p-form-model-item label="当前状态">
            <span>
              {{ currStatus === '0' || currStatus === '1' ? '草稿' : '审批中' }}
            </span>
          </p-form-model-item>
          <p-form-model-item label="销售组" prop="salesGroup">
            <SelectOrg
              v-model="form.salesGroup"
              :has-default="false"
              :parent-id="parentId"
              :options="orgGroupOptions"
              @input="changeHandle"
            />
          </p-form-model-item>
        </div>
        <!-- <div style="clear: both"></div> -->
      </div>
      <div style="width: 100%">
        <p-form-model-item label="价格变更简述" prop="priceChangeDescribe">
          <p-input v-model="form.priceChangeDescribe" placeholder="请输入" />
        </p-form-model-item>
      </div>
    </p-form-model>
  </div>
</template>

<script>
import monent from 'moment';
import MonthRangePickerPrice from '@/components/picker/MonthRangePickerPrice.vue';
import { getUserGroup } from '@/api/public.js';

export default {
  components: { MonthRangePickerPrice },
  props: {
    resForm: {
      type: Boolean,
      default: false,
    },
    isEmptyArray: {
      type: Boolean,
      default: false,
    },
    planType: {
      type: String,
      default: 'BP',
    },
    formInfo: {
      type: Object,
      default: () => ({}),
    },
    // currStatus: {
    //   type: [String, Number],
    //   default: '',
    // },
  },
  data() {
    return {
      options: [],
      hasAll: false,
      currStatus: '0',
      form: {
        serialNumber: '',
        salesOrganization: '',
        startTime: '',
        endTime: '',
        // salesGroup: {
        //   key: '',
        //   label: '',
        // },
        salesGroup: '',
        salesGroupName: '',
        priceChangeDescribe: '',
      },
      parentId: '',
      rules: {
        salesOrganization: [
          { required: true, message: '请选择销售组织', trigger: 'change' },
        ],
        salesGroup: [
          { required: true, message: '请选择销售组', trigger: 'change' },
        ],
        startTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value && this.form.endTime) {
                callback();
              } else {
                callback(new Error(rule.message));
              }
            },
            message: '请选择变更年月',
            trigger: 'change',
          },
        ],
        priceChangeDescribe: [
          { required: true, message: '请输入价格变更简述', trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    orgGroupOptions() {
      return this.$store.getters.getOrg({
        code: this.parentId,
        type: 'sales',
        isDict: false,
      });
    },
    orgGroup() {
      return this.$store.getters.getOrg({
        code: this.parentId,
        type: 'sales',
      });
    },

    uid() {
      return this.$store.state.user.uid;
    },
    stateOptions() {
      return this.$store.state.dictionary.dict['state'] || {};
    },
  },
  watch: {
    form: {
      handler(val) {
        this.$emit('get-form', val);
      },
      deep: true,
    },
    formInfo: {
      handler(val) {
        this.form.serialNumber = val.serialNumber;
        this.form.salesOrganization = val.salesOrganization;
        this.form.startTime = val.startTime;
        this.form.endTime = val.endTime;
        this.form.salesGroup = val.salesGroup;
        this.form.salesGroupName = val.salesGroupName;
        this.form.priceChangeDescribe = val.priceChangeDescribe;
        this.parentId = val.salesOrganization;
        this.currStatus = val.currStatus;
      },
      deep: true,
    },
    resForm: {
      handler(val) {
        if (val) {
          this.form = {
            serialNumber: '',
            salesOrganization: '',
            startTime: '',
            endTime: '',
            salesGroup: '',
            priceChangeDescribe: '',
          };
          this.parentId = '';
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getCurrentUser();
  },
  methods: {
    selectTime() {
      console.log('点击了时间');
    },
    async getCurrentUser() {
      const result = await getUserGroup(this.uid);
      const data = result?.data?.data;
      if (data.org.length === 1) {
        this.form.salesOrganization = Object.keys(data.org[0].ltcorg)[0];
        this.parentId = Object.keys(data.org[0].ltcorg)[0];
        const salesKeys = Object.keys(data.org[0].salesgroup);
        if (salesKeys.length === 1) {
          this.form.salesGroup = salesKeys[0];
          this.form.salesGroupName = data.org[0].salesgroup[salesKeys[0]];
        }
      }
    },
    changeHandle(val, isDefault) {
      if (this.form.salesGroup && !isDefault && this.isEmptyArray) {
        this.$confirm('该操作将清空价格变更明细，是否确认？')
          .then(() => {
            this.form.salesGroup = val;
            this.$emit('update:isEmptyArray', false);
            this.$emit('res-data');
          })
          .catch(() => {
            // console.log('e: ', e);
          });
      } else {
        this.form.salesGroup = val;
      }
    },
    resIsEmptyArray() {
      this.$emit('update:isEmptyArray', false);
      this.$emit('res-data');
    },
    disabledDate(val) {
      return monent().endOf('day').subtract(1, 'day').valueOf() > val.valueOf();
    },
    async handleOrgChange(val, isDefault) {
      console.log('val: ', val);
      // if (typeof val === 'object') {
      //   console.log('val: ', val);
      //   this.form.salesOrganization = val.cur;
      //   this.form.salesGroup = {
      //     key: val.orgCode,
      //     label: val.salesGroupLabel,
      //   };
      //   this.parentId = val.cur;
      //   this.hasAll = true;
      // } else {
      if (this.form.salesGroup.key && !isDefault && this.isEmptyArray) {
        this.$confirm('该操作将清空价格变更明细，是否确认？')
          .then(() => {
            this.form.salesOrganization = val;
            this.parentId = val;
            this.form.salesGroup = '';
            this.orgGroupOptions = [];
            this.$emit('update:isEmptyArray', false);
            this.$emit('res-data');
          })
          .catch(() => {
            // console.log('e: ', e);
          });
      } else {
        this.form.salesOrganization = val;
        this.parentId = val;
        this.form.salesGroup = '';
        this.orgGroupOptions = [];
      }
      // }
    },
    // async getDicList() {
    //   const result = await postOrganizationInfo({
    //     code: this.parentId || 'ltcsmsizebu',
    //   });

    //   const orgOptions = result?.data?.data || [];
    //   this.orgOptions = orgOptions.reduce((pre, cur) => {
    //     pre[cur.code] = cur.name;
    //     return pre;
    //   }, {});
    //   this.orgGroupOptions = orgOptions.filter((item) =>
    //     item.code?.includes('sales')
    //   );
    // },
    setForm(serialNumber) {
      this.form.serialNumber = serialNumber;
    },
    validate() {
      return new Promise((resolve) => {
        this.$refs.form.validate((valid) => {
          resolve(valid);
        });
      });
    },
    handleRangeChange(value) {
      this.form.startTime = value;
    },
    handleDeadLineChange(value) {
      const formatTime = monent(value).format('YYYY-MM-DD 23:59:59');
      this.form.deadlineTime = formatTime;
    },
    handleDeadLineOk(value) {
      const formatTime = monent(value).format('YYYY-MM-DD 23:59:59');
      this.form.deadlineTime = formatTime;
    },
  },
};
</script>

<style lang="less" scoped>
.connect {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.poros-form-item {
  display: flex;
  //   margin-bottom: 10px;
}
.item {
  width: 48%;
}
// .poros-form-item {
//   width: 48%;
// }
/deep/ .poros-form-item-label {
  width: 120px;
  margin-right: 20px;
}
/deep/ .poros-form-item-control-wrapper {
  width: calc(100% - 180px);
}
</style>
